//
//  UserDetailVC.swift
//  YueChat
//
//  Created by IMac on 2024/9/18.
//

import UIKit

class UserDetailVC: BaseVC {

    var userInfo = DMCCUser()
    
    init(userInfo: DMCCUser = DMCCUser()) {
        super.init(nibName: nil, bundle: nil)
        self.userInfo = userInfo
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.updateUserinfo()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = "好友资料"
        
        Task {
            let user = await gosnUser.fetchUserInfo(userInfo.userId)
            await MainActor.run {
                if user != nil {
                    GK_main_async_safe {
                        self.userInfo = user!
                        self.tableView.reloadData()
                    }
                }
            }
                
        }
        
        setup()
    }
    
    func updateUserinfo () {
        
        self.userInfo = gosnUser.getUserInfoDefault(userInfo.userId)
        GK_main_async_safe {
            self.tableView.reloadData()
        }
        
//        gosnUser.getUserInfo(self.userInfo.userId, refresh: false) { a in
//            if a != nil {
//                self.userInfo = a as! UserInfo
//                GK_main_async_safe {
//                    self.tableView.reloadData()
//                }
//            }
//        } error: { e in
//            
//        }

    }


    func setup () {
        dataSource = [["head","备注","推荐给朋友"],["二维码"],["加入黑名单","投诉"],["发消息"],["删除联系人"]]
        
        tableView.dataSource = self
        tableView.delegate = self
        tableView.register(UINib(nibName: "UserCell", bundle: nil), forCellReuseIdentifier: "UserCell")
        tableView.register(UINib(nibName: "SubTitleCell", bundle: nil), forCellReuseIdentifier: "SubTitleCell")
        tableView.register(UINib(nibName: "SwitchCell", bundle: nil), forCellReuseIdentifier: "SwitchCell")
        tableView.register(UINib(nibName: "LogoutCell", bundle: nil), forCellReuseIdentifier: "LogoutCell")
    }
    

  
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if indexPath.section == 0 && indexPath.row == 0 {
            return 120
        }
        
        return 60
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return dataSource.count
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let array = dataSource[section] as! Array<String>
        return array.count
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.001
    }
    
//    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
//        let view = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 10))
//        view.backgroundColor = UIColor.lightGray
//        return view
//    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 10
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            
        let array = self.dataSource[indexPath.section] as! Array<String>
        let name = array[indexPath.row]
        if indexPath.section == 0 && indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "UserCell", for: indexPath) as! UserCell
            cell.setUserInfo(userInfo: self.userInfo)
            cell.imgWidth.constant = 70
            cell.imgHeight.constant = 70
            return cell
        }
        
        if indexPath.section == 2 && indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchCell", for: indexPath) as! SwitchCell
            cell.titleLab.text = name
            cell.type = .BlackType
            cell.userInfo = self.userInfo
            cell.sw.setOn((gosnFriend.isBlacked(userInfo.userId)), animated: true)
           
            return cell
        }
        
        if indexPath.section == 3  || indexPath.section == 4{
            let cell = tableView.dequeueReusableCell(withIdentifier: "LogoutCell", for: indexPath) as! LogoutCell
            cell.titleLab.text = name
            
            if indexPath.section == 3 {
                cell.titleLab.font = UIFont.systemFont(ofSize: 18, weight: .semibold)
                cell.titleLab.textColor = UIColor.MainColor
            }else if indexPath.section == 4{
                cell.titleLab.textColor = UIColor.red
            }
            return cell
        }
        
        let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
        cell.contentView.backgroundColor = UIColor.clear
        cell.accessoryType = .disclosureIndicator
        cell.textLabel?.text = name
        return cell
        
        
        
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        tableView.deselectRow(at: indexPath, animated: true)
        
        
        if (indexPath.section == 0  && indexPath.row == 0) {
            if userInfo.getNft()!.count > 0 {
                self.navigationController?.pushViewController(PrivacyWebVC(string: userInfo.getNft()!), animated: true)
            }
            
        }else if (indexPath.section == 0  && indexPath.row == 1) {
            self.presentVC(VC: SetNickNameVC(type: .user, SId: self.userInfo.userId, dismissCompletion: {
                self.updateUserinfo()
            }))
        } else if (indexPath.section == 0 && indexPath.row == 2) {
            let vc = ShareUserVC(curentUser: self.userInfo, curentGroup: DMCCGroup())
            vc.isContact = true
            self.presentVC(VC: vc)
        } else if (indexPath.section == 1) {
            let con = gosnConversation.newConversation(OsnConversationType.Single, userInfo.userId)
            navigationController?.pushViewController(QRVC(with: con, isGroup: false, isUser: true), animated: true)
        } else if (indexPath.section == 0 && indexPath.row == 2) {
    //        [self.navigationController pushViewController:[[MHHYTagOperateVC alloc] initWithTagAddInfo:self.userInfo] animated:YES];
        } else if (indexPath.section == 2) {
            if indexPath.row == 1 {
                self.navigationController?.pushViewController(ReportVC(isGroup: false), animated:  true)
            }
        }else if indexPath.section == 3 {
            // 假设 self.userInfo 是一个有效的 UserInfo 实例
            // 假设 DMCCIMService 是一个单例，并且有 getConversation 和 insertConversationWithUser 方法
            
            
            let conversation = gosnConversation.getConversationInfoDefault(self.userInfo.userId)//gosnConversation.initParam(self.userInfo.userId)

            // 创建 MHHYSingleChatVC 实例
            let vc = ChatVC(conversation: conversation)

            // 推送新的视图控制器到导航堆栈中
            self.navigationController?.pushViewController(vc, animated: true)
        }else if indexPath.section == 4 {
            let str = KLocalizedString("将联系人删除，同时删除聊天记录")
            MHAlert.showCustomAlert(str) { ac in
                if ac.title == KLocalizedString("Sure") {
                    self.deleUserClick()
                }
            }
        }
    }
    
    
    func deleUserClick() {
        let ws = self
        MHAlert.showLoadingStr(KLocalizedString("ContactDeleteUserMsg"))
        Task{
            let res = await gosnFriend.deleteFriend(self.userInfo.userId)
            await MainActor.run {
                if res {
                    geventService.post(.kUpDateConversation, "")
                    NotificationCenter.default.post(name: Notification.Name(rawValue: kDeleteUserChanged), object: nil)
                    DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                        ws.navigationController?.popToRootViewController(animated: true)
                    }
                    MHAlert.showMessage(KLocalizedString("ContactDeleteUserSuccess"))
                }else{
                    MHAlert.showMessage(KLocalizedString("ContactDeleteUserError"))
                }
            }
        }
    }

}
